﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace TabletopWidgetTestApp
{
    //public delegate void DwellCallback(Object);
    
    public static class Dwell
    {
        private static Dictionary<UIElement, DispatcherTimer> _timers;

        static Dwell()
        {
            _timers = new Dictionary<UIElement, DispatcherTimer>();
        }

        public static void Start(UIElement w, int duration, TimerCallback cb)
        {
            // Do not start a second timer if one already exists           
            if (!_timers.ContainsKey(w))
            {
                DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromMilliseconds(duration);
                timer.Tick += new EventHandler(delegate(object s, EventArgs a)
                {
                    cb(null);
                    Stop(w);
                });

                _timers.Add(w, timer);

                timer.Start();

                /*// Initialize the timer to not start automatically
                Timer tmrThreadingTimer = new Timer(cb, null, Timeout.Infinite, duration);

                // Add timer to dictionary mapping
                _timers.Add(w, tmrThreadingTimer);

                // Manually start the timer to run only ONCE and for duration length
                tmrThreadingTimer.Change(duration, Timeout.Infinite);*/
            }
        }

        public static void Stop(UIElement w)
        {
            if (_timers.ContainsKey(w))
            {
                _timers[w].Stop();
                _timers.Remove(w);

                /*// stop it from running again, to be explicit
                _timers[w].Change(Timeout.Infinite, Timeout.Infinite);

                // dispose of the resources
                _timers[w].Dispose();
                _timers.Remove(w);*/
            }
        }

        public static bool HasDwellTimer(UIElement w)
        {
            return _timers.ContainsKey(w);
        } 
    }
}
